import styled from "@emotion/styled";
import { useDocumentTitle } from "utils/common";
import logo from "images/logo.svg";
import left from "images/left.svg";
import right from "images/right.svg";
import { Button, Card, Form, Input } from "antd";
import { ErrorBox, Row } from "components/lib";
import { useCaptcha, useLogin } from "utils/login";
import { useState } from "react";
import MD5 from "js-md5";
import { localStorageTokenKey, useAuth } from "context/auth-context";

export const UnauthenticatedApp = () => {
  useDocumentTitle("请登录");
  const { mutateAsync: login, isLoading } = useLogin();
  const [error, setError] = useState<Error | null>(null);
  const [random, setRandom] = useState(Math.random);
  const { data: captchaData } = useCaptcha({ time: random });
  const { login: loginAfter } = useAuth();

  const handleSubmit = async (values: {
    username: string;
    password: string;
    captcha: string;
  }) => {
    const params = {
      ...values,
      password: MD5(values?.password),
      key: captchaData?.key,
    };
    login(params)
      .then((res) => {
        // 全局登录
        loginAfter(res.admin);
        window.localStorage.setItem(localStorageTokenKey, res.token);
      })
      .catch((error) => {
        // 显示错误消息
        setError(new Error(error?.message));
        // 重置验证
        setRandom(Math.random);
      });
  };

  return (
    <Container>
      <Header />
      <Background />
      <ShadowCard>
        <Title>请登录</Title>
        <ErrorBox error={error} />
        <Form onFinish={handleSubmit}>
          <Form.Item
            name={"username"}
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder={"用户名"} type={"text"} id={"username"} />
          </Form.Item>
          <Form.Item
            name={"password"}
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input placeholder={"密码"} type={"password"} id={"password"} />
          </Form.Item>
          <Form.Item
            name={"captcha"}
            rules={[{ required: true, message: "请输入验证码" }]}
          >
            <Row between={true}>
              <Input
                style={{ width: "50%" }}
                placeholder={"验证码"}
                type={"text"}
                id={"captcha"}
              />
              <img
                onClick={() => setRandom(Math.random)}
                style={{ cursor: "pointer", height: "30px" }}
                src={captchaData?.img}
                loading={"lazy"}
                alt="验证码"
              />
            </Row>
          </Form.Item>
          <Form.Item>
            <LongButton
              loading={isLoading}
              htmlType={"submit"}
              type={"primary"}
            >
              登录
            </LongButton>
          </Form.Item>
        </Form>
      </ShadowCard>
    </Container>
  );
};

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
`;

const Header = styled.header`
  background: url(${logo}) no-repeat center;
  padding: 5rem 0;
  background-size: 20rem;
  width: 100%;
`;

const Background = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: left bottom, right bottom;
  background-size: calc(((100vw - 40rem) / 2) - 3.2rem),
    calc(((100vw - 40rem) / 2) - 3.2rem), cover;
  background-image: url(${left}), url(${right});
`;

const ShadowCard = styled(Card)`
  width: 40rem;
  min-height: 40rem;
  padding: 3.2rem 4rem;
  border-radius: 0.3rem;
  box-sizing: border-box;
  box-shadow: rgba(0, 0, 0, 0.1) 0 0 10px;
`;

const Title = styled.h2`
  margin-bottom: 2.4rem;
  text-align: center;
  color: rgb(94, 108, 132);
`;

const LongButton = styled(Button)`
  width: 100%;
`;
